<?php

namespace app\admin\controller\mall;

use app\api\model\mysql\MallUser;
use app\common\controller\AdminController;
use app\common\model\MallCommissionLevel;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;

/**
 * @ControllerAnnotation(title="mall_user")
 */
class User extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\MallUser();
        
        $this->assign('getTypeList', $this->model->getTypeList());

        $this->assign('getStatusList', $this->model->getStatusList());
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k=>$v){
                $levelinfo =(new MallCommissionLevel())->getlevelInfo($v['commission_level']);
                $list[$k]['levelname'] =$levelinfo['levelname'];
                $minfo =(new MallUser())->alias('u')->field('m.nickName')->join('mall_user m','m.id=u.parent_id')->where("u.openid",$v['openid'])->find();
                if($minfo){
                    $list[$k]['parent_name'] =$minfo['nickName'];
                }else{
                    $list[$k]['parent_name'] ='';
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                if($post['commission_level']!=$row['commission_level']){
                    $post['level_time']=time();
                }
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);

        $rankList =(new MallCommissionLevel())->field('id,levelname')->select()->toArray();
        $this->assign('rankList', $rankList);
        return $this->fetch();
    }
}